import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test3 {
    //leetcode 446 等差数列划分II - 子序列
    public int numberOfArithmeticSlices(int[] nums) {
        int n = nums.length;
        int[][] dp = new int[n][n];
        //这个题目因为要计算的是等差数列的个数，所以我们需要将所有相等的数的下标都存进哈希表中
        Map<Long, List<Integer>> hash = new HashMap<>();
        for (int i = 0; i < n; i++) {
            Long tmp = (long)nums[i];
            if (!hash.containsKey(tmp)) hash.put(tmp,new ArrayList<Integer>());
            hash.get(tmp).add(i);
        }
        int ret = 0;
        for (int j = 2; j < n; j++) {
            for (int i = 1; i < j; i++) {
                long a = 2L * nums[i] - nums[j];
                if (hash.containsKey(a)) {
                    for (int k : hash.get(a)) {
                        if (k < i) dp[i][j] += dp[k][i] + 1;
                        else break;
                    }
                    ret += dp[i][j];
                }
            }
        }
        return ret;
    }
}
